iT邦幫忙

2023 iThome 鐵人賽

DAY 14
0
自我挑戰組

設計模式系列 第 14

Day14 - 代理模式(Proxy pattern)

  • 分享至 

  • xImage
  •  

介紹
代理模式對目標物件提供額外的存取限制。

C++範例

#include <iostream>
#include <memory>

class IWeapon
{
public:
    virtual ~IWeapon()
    {
        std::cout << "IWeapon destructor called" << std::endl;
    }

    virtual void Equip() = 0;
};

class KingSword : public IWeapon
{
public:
    void Equip() override
    {
        std::cout << "King sword equipped" << std::endl;
    }
};

class KingSwordProxy : public IWeapon
{
public:
    KingSwordProxy(int playerLevel) :
        m_PlayerLevel(playerLevel),
        m_Weapon(std::make_unique<KingSword>())
    {
    }

    void Equip() override
    {
        if (m_PlayerLevel >= 30)
        {
            m_Weapon->Equip();
        }
        else
        {
            std::cout << "You need to reach level 30 to use this weapon" << std::endl;
        }
    }

private:
    int m_PlayerLevel;
    std::unique_ptr<IWeapon> m_Weapon;
};

int main()
{
    // Player is level 23
    std::unique_ptr<IWeapon> weapon = std::make_unique<KingSwordProxy>(23);
    weapon->Equip();

    // Player is level 30
    weapon = std::make_unique<KingSwordProxy>(30);
    weapon->Equip();

    return 0;
}

Output:

You need to reach level 30 to use this weapon
IWeapon destructor called
IWeapon destructor called
King sword equipped
IWeapon destructor called
IWeapon destructor called

上一篇
Day13 - 享元模式(Flyweight pattern)
下一篇
Day15 - 責任鏈模式(Chain of responsibility pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言